﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

/// <summary>
/// Helper 的摘要说明
/// </summary>
public static class Helper
{
    /// <summary>
    /// 记录日志
    /// </summary>
    /// <param name="strMemo"></param>
    //public static void WriteLog(string strMemo)
    //{
    //    string directoryPath = HttpContext.Current.Server.MapPath(@"\Logs");
    //    string fileName = directoryPath + @"\log" + DateTime.Today.ToString("yyyyMMdd") + ".txt";
    //    if (!Directory.Exists(directoryPath))
    //        Directory.CreateDirectory(directoryPath);
    //    StreamWriter sr = null;
    //    try
    //    {
    //        if (!File.Exists(fileName))
    //        {
    //            sr = File.CreateText(fileName);
    //        }
    //        else
    //        {
    //            sr = File.AppendText(fileName);
    //        }
    //        sr.WriteLine(DateTime.Now + ": " + strMemo);
    //    }
    //    catch (Exception ex)
    //    {
    //    }
    //    finally
    //    {
    //        if (sr != null)
    //            sr.Close();
    //    }
    //}

    /// <summary>
    /// 获取emsb帮你请求的token
    /// </summary>
    /// <returns></returns>
    public static string GetAccessToken()
    {
        string VERSION = "1";
        string CONSUMER_CODE = "CS-1/65/S0471-006";
        string MKey = "ff8080814e4cd26c015185db0f2e011a";
        string SERVICE_CODE = "s-000127";
        string parma = "\"DATA\":{}";
        string result = GetHttpDdata(MKey, SERVICE_CODE,VERSION,CONSUMER_CODE, parma);
        if (result.Contains("OK"))
        {
            List<dkidfk> tokenTiack = new List<dkidfk>();
            JObject jo = JObject.Parse(result);
            result = jo["ESBRESP"]["DATA"]["getSignatureInfoResp"]["items"].ToString();
            if (result != "" && result != null)
            {
                tokenTiack = JsonConvert.DeserializeObject<List<dkidfk>>(result);
                if (tokenTiack.Count > 0)
                {
                    foreach (var item in tokenTiack)
                    {
                        result = item.accessToken;
                    }
                }

            }
        }
        return result;
    }

    /// <summary>
    /// 获取emsb帮你请求的ticket
    /// </summary>
    /// <returns></returns>
    public static string GetjsapiTicket()
    {
        string VERSION = "1";
        string CONSUMER_CODE = "CS-1/65/S0471-006";
        string MKey = "ff8080814e4cd26c015185db0f2e011a";
        string SERVICE_CODE = "s-000127";
        string parma = "\"DATA\":{}";
        string result = GetHttpDdata(MKey, SERVICE_CODE, VERSION, CONSUMER_CODE, parma);
        if (result.Contains("OK"))
        {
            List<dkidfk> tokenTiack = new List<dkidfk>();
            JObject jo = JObject.Parse(result);
            result = jo["ESBRESP"]["DATA"]["getSignatureInfoResp"]["items"].ToString();
            if (result != "" && result != null)
            {
                tokenTiack = JsonConvert.DeserializeObject<List<dkidfk>>(result);
                if (tokenTiack.Count > 0)
                {
                    foreach (var item in tokenTiack)
                    {
                        result = item.jsapiTicket;
                    }
                }

            }
        }
        return result;
    }

    /// <summary>
    /// 返回一个八位的随机号，用于签名
    /// </summary>
    /// <returns></returns>
    public static string randNonce()
    {
        var result = "";
        var random = new Random((int)DateTime.Now.Ticks);
        const string textArray = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

        for (var i = 0; i < 8; i++)
        {
            result = result + textArray.Substring(random.Next() % textArray.Length, 1);
        }

        return result;
    }

    /// <summary>
    /// 时间戳的随机数
    /// </summary>
    /// <returns></returns>
    public static string timeStamp()
    {
        DateTime dt1 = Convert.ToDateTime("1970-01-01 00:00:00");
        TimeSpan ts = DateTime.Now - dt1;
        return Math.Ceiling(ts.TotalSeconds).ToString();
    }

    /// <summary>
    /// state 随机数
    /// </summary>
    /// <returns></returns>
    public static string state()
    {
        Random ran = new Random();
        int RandKey = ran.Next(100, 999);
        return RandKey.ToString();
    }

    /// <summary>
    /// 生成发送时间，供调用接口时使用
    /// </summary>
    /// <returns></returns>
    public static string DTSEND()
    {
        DateTime dtDtsend = DateTime.Now;
        string strDtsend = dtDtsend.ToString().Replace(":", "").Replace("/", "").Replace(" ", "") + "000";
        return strDtsend;
    }

    /// <summary>
    /// 调用总线接口返回业绩数据
    /// </summary>
    public static string GetHttpDdata(string miyao, string SERVICE_CODE, string VERSION, string CONSUMER_CODE, string param)
    {
        string dtsend = DTSEND();
        string url = "" + Config.WebUrl;//+ "/httphub"
        string postData = "{\"ESBREQ\":{\"HEADER\":{\"SERVICE_CODE\":\"" + SERVICE_CODE + "\",\"VERSION\":\"" + VERSION + "\",\"CONSUMER_CODE\":\"" + CONSUMER_CODE + "\",\"PASSWORD\":\"" + PASSWORD(miyao, SERVICE_CODE, VERSION, CONSUMER_CODE, dtsend) + "\",\"MESSAGE_ID\":\"" + MESSAGE_ID() + "\",\"DTSEND\":\"" + dtsend + "\",\"EXT1\":\"\",\"EXT2\":\"\",\"EXT3\":\"\"}," + param + "}}";
        //WebRequest request = WebRequest.Create(url);
        //request.Method = "Post";
        //request.ContentType = "application/json;charset=UTF-8";
        //request.ContentLength = postData.Length;
        //StreamWriter sw = new StreamWriter(request.GetRequestStream());            
        //sw.Write(postData);
        //sw.Flush();
        //WebResponse response = request.GetResponse();
        //Stream s = response.GetResponseStream();
        //StreamReader sr = new StreamReader(s, Encoding.GetEncoding("UTF-8"));
        //string str = sr.ReadToEnd();
        string str = HttpHelper.Post(url, postData);
        //sw.Dispose();
        //sw.Close();
        //sr.Dispose();
        //sr.Close();
        //s.Dispose();
        //s.Close();
        return str;
    }
    /// <summary>
    /// 调用接口的参数 消费契约中的服务访问密码 调用同一个接口时不需要重新生成
    /// </summary>
    /// <returns></returns>
    public static string PASSWORD(string miyao, string SERVICE_CODE, string VERSION, string CONSUMER_CODE, string dtsend)
    {
        StringBuilder strPwd = new StringBuilder();
        StringBuilder strPassword = new StringBuilder();
        strPassword.Append(miyao);
        strPassword.Append("SERVICE_CODE");
        strPassword.Append(SERVICE_CODE);
        strPassword.Append("VERSION");
        strPassword.Append(VERSION);
        strPassword.Append("CONSUMER_CODE");
        strPassword.Append(CONSUMER_CODE);
        strPassword.Append("MESSAGE_ID");
        strPassword.Append(MESSAGE_ID());
        strPassword.Append("DTSEND");
        strPassword.Append(dtsend);
        strPassword.Append("EXT1EXT2EXT3");
        strPassword.Append(miyao);
        MD5 md5 = MD5.Create();
        byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(strPassword.ToString()));
        for (int i = 0; i < s.Length; i++)
        {
            // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 
            strPwd = strPwd.Append(s[i].ToString("X2"));
        }

        return strPwd.ToString();
    }
    /// <summary>
    /// 生成一个 消息ID 供调用接口时使用
    /// </summary>
    /// <returns></returns>
    public static string MESSAGE_ID()
    {
        StringBuilder strMessageID = new StringBuilder();
        for (int i = 0; i < 32; i++)
        {
            Random rand = new Random(i);
            int number = rand.Next(0, 2);//随机生成0和1，判断下一位字符是数字还是字母
            if (number == 0)//数字
            {
                strMessageID.Append(rand.Next(0, 9));
            }
            else//字母
            {
                strMessageID.Append(Convert.ToChar(rand.Next(65, 91)));
            }
        }
        return strMessageID.ToString();
    }



}
#region
public class dkidfk
{
    public string accessToken { get; set; }
    public string jsapiTicket { get; set; }
}
#endregion